package br.com.pyramides.controller;

import br.com.pyramides.facade.EventoFacade;
import br.com.pyramides.facade.UsuarioFacade;
import br.com.pyramides.facade.iface.IEventoFacade;
import br.com.pyramides.facade.iface.IUsuarioFacade;
import br.com.pyramides.form.EventoForm;
import br.com.pyramides.model.Evento;
import br.com.pyramides.model.Usuario;
import br.com.pyramides.utils.Constants;
import br.com.pyramides.utils.DataHoraUtil;
import br.com.pyramides.utils.Funcoes;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.MaskFormatter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author Lessandro
 */
public class EventoAction extends DispatchAction {

    private Log logger = LogFactory.getLog(this.getClass());
    private IEventoFacade eventoService;
    private IUsuarioFacade usuarioService;

    public ActionForward getEventos(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("getEventos");
        eventoService = new EventoFacade();
        long idUsuario = Long.parseLong(request.getParameter("idUsuario"));
        List<Evento> eventos = eventoService.listaEventos(idUsuario);
        request.setAttribute(Constants.USUARIO, idUsuario);
        request.setAttribute(Constants.EVENTOS, eventos);
        return mapping.findForward(Constants.SUCCESS);
    }

    public ActionForward setaInsercaoEdicaoEvento(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("setaInsercaoEdicaoEvento");
        EventoForm eventoForm = (EventoForm) form;
        long idUsuario = request.getParameter("idUsuario") != null ? Long.parseLong(request.getParameter("idUsuario")) : 0;
        long idEvento = request.getParameter("idEvento") != null ? Long.parseLong(request.getParameter("idEvento")) : 0;
        request.setAttribute(Constants.USUARIO, idUsuario);
        eventoForm.setId(idEvento);
        Evento evento = null;
        if (isUpdate(request, eventoForm)) {
            Long id = eventoForm.getId();
            eventoService = new EventoFacade();
            evento = eventoService.buscaPeloID(id);
            eventoForm.setId(idEvento);
            eventoForm.setIdUsuario(evento.getUsuario().getIdUsuario());
            eventoForm.setNome(evento.getNome());
            eventoForm.setDescricao(evento.getDescricao());
            eventoForm.setCidade(evento.getCidade());
            eventoForm.setLocal(evento.getLocal());
            eventoForm.setNomePromotor(evento.getNomePromotor());
            eventoForm.setObservacao(evento.getObservacao());
            if (evento.getTelContato() != null) {
                String telFormatado = Funcoes.formatString(evento.getTelContato().toString(), "(##) ####-####");
                eventoForm.setTelefone(telFormatado);
            }
            String dataFormatada = evento.getDataEvento() != null ? DataHoraUtil.formataDataEmString(evento.getDataEvento()) : new String();
            eventoForm.setData(dataFormatada);
        }
        return mapping.findForward("showForm");
    }

    public ActionForward remover(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("remover");
        long idUsuario = Long.parseLong(request.getParameter("idUsuario"));
        long idEvento = Long.parseLong(request.getParameter("idEvento"));
        eventoService = new EventoFacade();
        Evento evento = eventoService.buscaPeloID(idEvento);
        eventoService.exclui(evento);
        final ActionForward successAction = mapping.findForward("showList");
        ActionForward modifiedSuccessAction = new ActionForward();
        modifiedSuccessAction.setName(successAction.getName());
        modifiedSuccessAction.setPath(successAction.getPath() + "?idUsuario=" + idUsuario + "&dispatch=getEventos");
        modifiedSuccessAction.setRedirect(true);
        return modifiedSuccessAction;
    }

    public ActionForward insereAtualiza(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("insereAtualiza");
        EventoForm eventoForm = (EventoForm) form;

        if (validaForm(request, eventoForm)) {

            Evento evento = new Evento();
            evento.setIdEvento(eventoForm.getId());
            evento.setNome(eventoForm.getNome());
            evento.setDescricao(eventoForm.getDescricao());
            evento.setCidade(eventoForm.getCidade());
            evento.setLocal(eventoForm.getLocal());
            evento.setNomePromotor(eventoForm.getNomePromotor());
            evento.setObservacao(eventoForm.getObservacao());
            if (eventoForm.getTelefone() != null && !eventoForm.getTelefone().isEmpty()) {
                BigInteger telContato = new BigInteger(Funcoes.removeCaracteresEspeciais(eventoForm.getTelefone()));
                evento.setTelContato(telContato);
            }
            usuarioService = new UsuarioFacade();
            long idUsuario = Long.parseLong(request.getParameter("idUsuario"));
            Usuario usuario = usuarioService.buscaPeloID(idUsuario);
            evento.setUsuario(usuario);
            request.setAttribute(Constants.USUARIO, idUsuario);            
            Date data = DataHoraUtil.formataStringEmData(eventoForm.getData());
            evento.setDataEvento(data);

            eventoService = new EventoFacade();

            if (isUpdate(request, eventoForm)) {
                logger.debug("atualiza");
                eventoService.atualiza(evento);
            } else {
                logger.debug("grava");
                eventoService.salva(evento);
            }
            return mapping.findForward(Constants.SUCCESS);
        } else {
            return mapping.findForward(Constants.FAILURE);
        }
    }

    private boolean validaForm(HttpServletRequest request, EventoForm form) {
        boolean isOk = true;
        ActionMessages errors = new ActionMessages();
        if (form.getNome() == null || form.getNome().isEmpty()) {
            errors.add("nome", new ActionMessage("errors.required", "Nome"));
        }

        if (form.getDescricao() == null || form.getDescricao().isEmpty()) {
            errors.add("descricao", new ActionMessage("errors.required", "Descrição"));
        }
        if (form.getData() == null || form.getData() != null && form.getData().isEmpty()) {
            errors.add("data", new ActionMessage("errors.required", "Data"));
        }
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            isOk = false;
        }
        return isOk;
    }

    private boolean isUpdate(HttpServletRequest request, EventoForm eventoForm) {
        boolean updateFlag = true;
        Long id = eventoForm.getId();
        if (id == null || id == 0) {
            updateFlag = false;
        }
        request.setAttribute("updateFlag", Boolean.valueOf(updateFlag));
        return updateFlag;
    }
}
